<?php 
namespace app\admin\controller;

use app\common\controller\Base64;
use think\Config;
use think\Exception;
use think\Db;
use app\common\controller\Classify;
use app\common\model\shop\ShopGoods;
use app\common\controller\Log;
use app\common\model\shop\ShopClassify;

class Goods extends Base
{
	/**
	 * 商品列表
	 * @return unknown
	 */
	public function goodsList()
	{
		$data = $this->request->post('');
		//初始化查询条件
		$where = ['state' => ['in',[1,2]]];
		if(!empty($data['goods_name'])) {
			$where['goods_name'] = ["like",'%'.$data['goods_name'].'%'];
		}
		if(!empty($data['state'])) {
			$where['state'] = $data['state'];
		}
		$list = ShopGoods::where($where)->order('state asc,id dese')->paginate()->toArray();
		foreach ($list['data'] as &$rows) {
			$classify_id = [$rows['parent_classify'],$rows['child_classify'],$rows['son_classify']];
			$rows['classify_name'] = ShopClassify::where(['id' => ['in',$classify_id]])->column('name');
			$rows['classify_name'] = implode('-', $rows['classify_name']);
		}
		return jsonSuccess($list);
	}
	
	/**
	 * 商品回收站
	 * @return unknown
	 */
	public function trashList()
	{
		$data = $this->request->post('');
		$where = ['state' => 0];
		if(!empty($data['goods_name'])) {
			$where['goods_name'] = ["like",'%'.$data['goods_name'].'%'];
		}
		$list = ShopGoods::where($where)->order('state asc,id dese')->paginate()->toArray();
		foreach ($list['data'] as &$rows) {
			$classify_id = [$rows['parent_classify'],$rows['child_classify'],$rows['son_classify']];
			$rows['classify_name'] = ShopClassify::where(['id' => ['in',$classify_id]])->column('name');
			$rows['classify_name'] = implode('-', $rows['classify_name']);
		}
		return jsonSuccess($list);
	}
	/**
	 * 获取分类列表
	 * @return unknown
	 */
	public function getTypes()
	{
		$classify = new Classify();
		$list = $classify->getClassifyList(true);
		return jsonSuccess($list);
	}
	
	/**
	 * 添加商品
	 * @throws Exception
	 * @return unknown
	 */
	public function addGoods()
	{
		$data = $this->request->post('');
		Db::startTrans();
		try{
			//dump($data);
			//检测商品信息合法性
			$res = $this->checkGoodsData($data);
			if($res)throw new Exception($res);
			$data['create_time'] = time();
			$data['update_time'] = time();
			if(empty($data['size_index']))$data['size_index'] = '[]';
			if(empty($data['size_content']))$data['size_content'] = '[]';
			ShopGoods::create($data);
			//添加日志
			Log::addLog(1, '添加商品【'.$data['goods_name'].'】');
			Db::commit();
		}catch (Exception $e){
			Db::rollback();
			return jsonError($e->getMessage());
		}
		return jsonSuccess('添加成功');
	}
	
	/**
	 * 检查商品数据合法性
	 * @param array $data
	 * @return string
	 */
	private function checkGoodsData($data)
	{
		if(!$data['goods_name'])return '商品名称不能为空';
		if(!$data['goods_key'])return '商品关键字不能为空';
		if(!$data['goods_stock'])return '商品库存不能为空';
		if(!$data['goods_price'])return '商品价格不能为空';
		if(!$data['goods_old_price'])return '商品划线价不能为空';
		if(!$data['goods_img'])return '商品图片不能为空';
		if(!$data['parent_classify'])return '请完善商品分类';
		if(!$data['son_classify'])return '请完善商品分类';
		if(!$data['child_classify'])return '请完善商品分类';
		if(!count($data['goods_carousel']))return '商品轮播图不能为空';
		foreach ($data['attrs'] as $val) {
			if(!$val['value'] || !$val['name'])return '商品属性不完整';
		}
		if($data['is_intergal'] && !$data['intergal'])return "请输入兑换商品所需积分";
	}
	
	/**
	 * 更改商品上架状态
	 * @return unknown
	 */
	public function setState()
	{
		$data = $this->request->post('');
		Db::startTrans();
		try {
			$update = ['update_time' => time()];
			switch ($data['state']) {
				case 0:
					$msg = '删除';
					$state = 0;
					break;
				case 1:
					$msg = '上架';
					$state = 1;
					break;
				case 2:
					$msg = '下架';
					$state = 2;
					break;
				case 3:
					$msg = '还原';
					$state = 1;
					break;
				case 9:
					$msg = '清除';
					$state = 9;
					break;
			}
			$update['state'] = $state;
			if(is_array($data['id'])) {
				ShopGoods::where(['id' => ['in',$data['id']]])->update($update);
			}else{
				$goods = ShopGoods::get($data['id']);
				$goods->save($update);
				//添加日志
				Log::addLog(2, $msg."商品【{$goods -> goods_name}】");
			}
			
			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			return jsonError($e->getMessage());
		}
		return jsonSuccess($msg.'商品成功');
	}
	
	/**
	 * 删除商品
	 * @return unknown
	 */
	public function deleteGoods()
	{
		$id = $this->request->post('id');
		Db::startTrans();
		try {
			$goods = ShopGoods::get($id);
			$goods -> save(['state' => 0,'update_time' => time(),'delete_time' => time()]);
			//添加日志
			Log::addLog(3, "删除商品【{$goods->goods_name}】");
			Db::commit();
		} catch (Exception $e){
			Db::rollback();
			return jsonError($e->getMessage());
		}
		return jsonSuccess('商品删除成功');
	}
	
	/**
	 * 还原商品
	 * @return unknown
	 */
	public function refreshGoods()
	{
		$id = $this->request->post('id');
		Db::startTrans();
		try {
			$goods = ShopGoods::get($id);
			$goods -> save(['state' => 1,'update_time' => time()]);
			//添加日志
			Log::addLog(2, "还原商品【{$goods->goods_name}】");
			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			return jsonError($e->getMessage());
		}
		return jsonSuccess('还原成功');
	}
	
	/**
	 * 
	 * @return unknown
	 */
	public function cleanGoods()
	{
		$id = $this->request->post('id');
		Db::startTrans();
		try {
			$goods = ShopGoods::get($id);
			$goods -> save(['state' => 9,'update_time' => time()]);
			//添加日志
			Log::addLog(2, "彻底清除商品【{$goods->goods_name}】");
			Db::commit();
		} catch (Exception $e) {
			Db::rollback();
			return jsonError($e->getMessage());
		}
		return jsonSuccess('还原成功');
	}
	
	/**
	 * 上传图片
	 * @return unknown
	 */
	public function upImage()
    {
		$data = $this->request->post('');
		$base64 = new Base64();
		$res = $base64 ->up_base64($data['img'], Config::get('path.goods'));
		return jsonSuccess($res);
	}
	
	/**
	 * 获取商品信息
	 * @return unknown
	 */
	public function getGoodsInfo()
	{
		$id = $this->request->post('id');
		$goods = ShopGoods::get($id);
		return jsonSuccess($goods);
	}
	
	/**
	 * 修改商品信息
	 * @throws Exception
	 * @return unknown
	 */
	public function updateGoods()
	{
		$data = $this->request->post('');
		Db::startTrans();
		try{
			//检测商品信息合法性
			$res = $this -> checkGoodsData( $data );
			if( $res )throw new Exception( $res );
			$data['update_time'] = time();
			if( strpos ( $data['goods_img'] , 'http' ) !== false ){
				unset ( $data['goods_img'] );
			}
			foreach ( $data['goods_carousel'] as &$row ) {
				if ( strpos ( $row , 'http' ) !== false ) {
					$str = 'http://' . $_SERVER[ ' HTTP_HOST ' ];
					$row = str_replace ( $str , '' , $row );
				}
			}
			ShopGoods::get( $data[ ' id ' ] ) -> save( $data );
			//添加日志
			Log::addLog(2, '修改商品【'.$data['goods_name'].'】');
			Db::commit();
		}catch ( Exception $e ){
			Db::rollback();
			return jsonError($e->getMessage());
		}
		return jsonSuccess('修改成功');
	}
}